<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue'
import axios from 'axios'

// 调整后：允许 schTime、state、rank 为可选字段
interface Schedule {
  schId: number
  schName: string
  schTime?: string
  gameId: number
  eventId: number
  state?: string
  rank?: number
}

interface Event {
  eventID: number
  eventName: string
}

interface Game {
  game_name: string
  games_id: number
  events: Event[]
}

const games = ref<Game[]>([])
const selectedGame = ref<number | 'all'>('all')
const selectedEvent = ref<number | 'all'>('all')
const schedules = ref<Schedule[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(4) // 每页显示4条数据

// 格式化日期显示的函数
const formatDateTime = (dateString: string) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return {
    date: `${year}-${month}-${day}`,
    time: `${hours}:${minutes}:${seconds}`
  };
}

const fetchScheduleData = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://localhost:8080/event/gamesEvents', {
      headers: { token: token || '' }
    })
    if (response.data.success) {
      games.value = response.data.data
    }
  } catch (error) {
    console.error('获取赛程数据失败:', error)
  }
}

const fetchSchedules = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    let url = ''
    const headers = { token: token || '' }
    
    if (selectedGame.value === 'all') {
      url = 'http://localhost:8080/schedule/listByOrganizer'
    } else if (selectedEvent.value === 'all') {
      url = `http://localhost:8080/schedule/listByGameId?gameId=${selectedGame.value}`
    } else {
      url = `http://localhost:8080/schedule/listByEventId?eventId=${selectedEvent.value}`
    }
    
    const response = await axios.get(url, { headers })
    
    // 直接检查返回的数据是否为数组
    if (Array.isArray(response.data)) {
      schedules.value = response.data
    } else {
      schedules.value = []
    }
    
  } catch (error) {
    console.error('获取赛程安排失败:', error)
    schedules.value = []
  } finally {
    loading.value = false
    currentPage.value = 1 // 重置到第一页
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(schedules.value.length / pageSize.value)
})

// 计算当前页的数据
const paginatedSchedules = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return schedules.value.slice(startIndex, endIndex)
})

const onGameChange = () => {
  selectedEvent.value = 'all'
}

const newSchedule = () => {
  const event = new CustomEvent('showGameEvent', {
    detail: { type: 'newSchedule' }
  });
  window.dispatchEvent(event);
}

const editSchedule = (schedule: Schedule) => {
  const event = new CustomEvent('showGameEvent', {
    detail: { type: 'editSchedule', data: schedule }
  });
  window.dispatchEvent(event);
}

const deleteSchedule = async (schedule: Schedule) => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.delete(`http://localhost:8080/schedule/delete?id=${schedule.schId}`, {
      headers: { 
        token: token || ''
      }
    })
    
    // 检查响应状态码或响应数据来判断是否删除成功
    if (response.status === 200 || response.data?.success) {
      alert('赛程删除成功')
      // 重新获取赛程数据以刷新列表
      await fetchSchedules()
    } else {
      alert('赛程删除失败: ' + (response.data?.message || '未知错误'))
    }
  } catch (error: any) {
    console.error('删除赛程失败:', error)
    // 根据错误响应判断是否删除成功
    if (error.response?.status === 200) {
      alert('赛程删除成功')
      await fetchSchedules()
    } else {
      alert('删除赛程时发生错误: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 页面切换函数
const changePage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

const displayedGames = computed(() => {
  return games.value
})

const displayedEvents = computed(() => {
  if (selectedGame.value === 'all') {
    return []
  } else {
    const game = games.value.find(g => g.games_id === selectedGame.value)
    return game ? game.events : []
  }
})

// 根据游戏ID获取游戏名称
const getGameName = (gameId: number) => {
  const game = games.value.find(g => g.games_id === gameId)
  return game ? game.game_name : `未知比赛(${gameId})`
}

// 根据游戏ID和项目ID获取项目名称
const getEventName = (gameId: number, eventId: number) => {
  const game = games.value.find(g => g.games_id === gameId)
  if (game) {
    const event = game.events.find(e => e.eventID === eventId)
    return event ? event.eventName : `未知项目(${eventId})`
  }
  return `未知项目(${eventId})`
}

watch([selectedGame, selectedEvent], () => {
  fetchSchedules()
})

onMounted(async () => {
  await fetchScheduleData()
  await fetchSchedules()
})
</script>

<template>
  <div class="schedule-container">
    <div class="filter-section">
      <div class="filter-item">
        <label for="game-select">选择比赛：</label>
        <select 
          id="game-select" 
          v-model="selectedGame" 
          @change="onGameChange"
          class="form-select"
        >
          <option value="all">全部比赛</option>
          <option 
            v-for="game in displayedGames" 
            :key="game.games_id" 
            :value="game.games_id"
          >
            {{ game.game_name }}
          </option>
        </select>
      </div>
      
      <div class="filter-item">
        <label for="event-select">选择项目：</label>
        <select 
          id="event-select" 
          v-model="selectedEvent" 
          :disabled="selectedGame === 'all'"
          class="form-select" 
        >
          <option value="all" v-if="selectedGame !== 'all'">全部项目</option>
          <option 
            v-for="event in displayedEvents" 
            :key="event.eventID" 
            :value="event.eventID"
          >
            {{ event.eventName }}
          </option>
        </select>
      </div>
      
      <div class="filter-item">
        <button class="new-schedule-btn" @click="newSchedule">新建赛程</button>
      </div>
    </div>
    
    <div class="schedule-display">
      <div v-if="loading" class="loading">
        赛程加载中...
      </div>
      
      <!-- 修正：直接判断数组长度 -->
      <div v-else-if="schedules.length === 0" class="no-schedules">
        暂无赛程安排 (schedules.length: {{ schedules.length }})
      </div>
      
      <div v-else class="schedules-list">
        <div 
          v-for="schedule in paginatedSchedules" 
          :key="schedule.schId"
          class="schedule-item"
        >
          <!-- 第一行：比赛名称、项目名称和轮次 -->
          <div class="schedule-game-event">
            <span class="game-name">{{ getGameName(schedule.gameId) }}</span>
            <span class="event-name">{{ getEventName(schedule.gameId, schedule.eventId) }}</span>
            <span class="schedule-rank" v-if="schedule.rank !== null">轮次: {{ schedule.rank }}</span>
            <span class="schedule-state">{{ schedule.state || '默认状态' }}</span>
          </div>
          
          <!-- 第二行：赛程名称在左，时间、状态和操作按钮在右 -->
          <div class="schedule-main-info">
            <h3 class="schedule-name">{{ schedule.schName }}</h3>
            
            <div class="schedule-meta">
              <div class="schedule-time" v-if="schedule.schTime">
                <div class="date-time-container">
                  <span class="date-part">{{ formatDateTime(schedule.schTime).date }}</span>
                  <span class="time-part">{{ formatDateTime(schedule.schTime).time }}</span>
                </div>
              </div>
              
              <span class="schedule-time" v-else>时间未设置</span>
            </div>

            <div class="schedule-actions">
                <button class="edit-btn" @click="editSchedule(schedule)">修改信息</button>
                <button class="delete-btn" @click="deleteSchedule(schedule)">删除赛程</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          :disabled="currentPage === 1" 
          @click="changePage(currentPage - 1)"
          class="page-button"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <button 
          :disabled="currentPage === totalPages" 
          @click="changePage(currentPage + 1)"
          class="page-button"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 原样式保持不变 */
.schedule-container {
  width: 95%;
  padding: 20px;
}

.schedule-container h2 {
  text-align: center;
  color: #31B310;
  margin-bottom: 30px;
}

.filter-section {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-item label {
  font-weight: bold;
  color: #333;
  white-space: nowrap;
}

.form-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  min-width: 200px;
}

.form-select:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.schedule-display {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.schedule-display h3 {
  color: #31B310;
  margin-bottom: 15px;
}

.new-schedule-btn {
  padding: 8px 16px;
  background-color: #31B310;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  white-space: nowrap;
}

.new-schedule-btn:hover {
  background-color: #2a990d;
}

.loading, .no-schedules {
  text-align: center;
  padding: 20px;
  color: #666;
}

.schedules-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.schedule-item {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
  background-color: #fafafa;
}

.schedule-game-event {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 15px;
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.schedule-game-event .game-name,
.schedule-game-event .event-name {
  flex: 1;
  text-align: center;
  font-weight: bold;
  color: #000;
  font-size: 18px;
}

.schedule-game-event .separator {
  display: flex;
  align-items: center;
  color: #999;
  flex: none;
}

.schedule-main-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  /* 移除背景色和背景框 */
  background: none;
  border: none;
  box-shadow: none;
  padding: 0;
}

.schedule-name {
  margin: 0 0 0 40px; /* 增加左外边距，使标题进一步向右移动 */
  color: #333;
  font-size: 28px;
  font-weight: bold;
}

.schedule-meta {
  display: flex;
  gap: 15px;
  font-size: 18px;
  font-weight: bold;
  align-items: center;
  flex-wrap: wrap;
}

.schedule-time {
  color: #333;
  font-weight: bold;
  text-align: center;
  margin-right: auto; /* 将时间部分往左移，但不影响按钮位置 */
}

.date-time-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 80px; /* 增加日期和时间之间的间隔 */
}

.schedule-time .date-part {
  font-size: 24px;
}

.schedule-time .time-part {
  font-size: 20px;
  color: #666;
}

.schedule-state {
  font-weight: bold;
  color: #31B310;
  font-size: 14px;
  background-color: #e8f5e9;
  padding: 3px 10px;
  border-radius: 12px;
  white-space: nowrap;
}

.schedule-rank {
  font-size: 16px;
  font-weight: bold;
  color: #666;
  margin-right: auto;
}

.schedule-actions {
  display: flex;
  gap: 10px;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-left: 10px;
}

.edit-btn {
  background-color: #31B310;
  color: white;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.edit-btn:hover {
  background-color: #2a990d;
}

.delete-btn:hover {
  background-color: #cc0000;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.page-button {
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-button:hover:not(:disabled) {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-button:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.page-info {
  color: #333;
  font-weight: bold;
}
</style>